import streamlit as st
from sqlmodel import SQLModel, Session, create_engine, select, Field

from model.user import User

# -------------------
# 数据库连接
# -------------------
# DATABASE_URL = "sqlite:///example_orm.db"
# engine = create_engine(DATABASE_URL)

# 确保引擎初始化只执行一次
if "engine" not in st.session_state:
    engine = create_engine("sqlite:///users.db", echo=True)
    SQLModel.metadata.create_all(engine)
    st.session_state.engine = engine
else:
    engine = st.session_state.engine
# 自动创建表（如果不存在）
def create_db_and_tables():
    SQLModel.metadata.drop_all(engine)
    SQLModel.metadata.create_all(engine)


# 初始化数据库（仅在应用启动时执行一次）
if "tables_created" not in st.session_state:
    create_db_and_tables()
    st.session_state.tables_created = True


# -------------------
# Streamlit 界面
# -------------------
def main():
    st.title("用户管理系统（ORM 版）")

    # 添加用户表单
    with st.form("添加用户"):
        name = st.text_input("姓名 *")
        age = st.number_input("年龄", min_value=0, max_value=150)
        email = st.text_input("邮箱 *").strip()
        password = st.text_input("密码 *").strip()
        if st.form_submit_button("提交"):
            if name and email:
                with Session(engine) as session:
                    user = User(name=name, age=age, email=email,password=password)
                    session.add(user)  # 类型校验会自动进行！
                    session.commit()
                st.success("✔️ 用户添加成功")
                st.rerun()  # 实时刷新列表
            else:
                st.warning("⚠️ 带 * 的为必填字段")

    # 用户列表与操作
    st.header("用户列表")
    with Session(engine) as session:
        users = session.exec(select(User)).all()  # 查询全部用户

    if not users:
        st.info("❄️ 数据库为空")
        return

    for user in users:
        col1, col2, col3, col4 = st.columns([3, 2, 6, 2])
        with col1:
            st.write(f"**{user.name}**")
        with col2:
            st.write(f"年龄: {user.age}") if user.age else None
        with col3:
            st.write(user.email)
        with col4:
            if st.button(f"删除##{user.id}"):  # ❌ 删除操作
                with Session(engine) as session:
                    user_to_del = session.get(User, user.id)
                    session.delete(user_to_del)
                    session.commit()
                st.rerun()
main()

# if __name__ == "__main__":
#     main()
